package com.atguigu.chapter05.sink;

import com.alibaba.fastjson.JSON;
import com.atguigu.bean.WaterSensor;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Properties;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/6/10 10:09
 */
public class Flink01_Sink_Kafka_1 {
    public static void main(String[] args) throws Exception {
        ArrayList<WaterSensor> waterSensors = new ArrayList<>();
        waterSensors.add(new WaterSensor("sensor_1", 1607527992000L, 20));
        waterSensors.add(new WaterSensor("sensor_1", 1607527994000L, 50));
        waterSensors.add(new WaterSensor("sensor_1", 1607527996000L, 50));
        waterSensors.add(new WaterSensor("aaaasensor_30", 1607527993000L, 10));
        waterSensors.add(new WaterSensor("sensor_2", 1607527995000L, 30));
        
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);
        
        Properties props = new Properties();
        props.setProperty("bootstrap.servers", "hadoop162:9092");
        env
            .fromCollection(waterSensors)
            .addSink(new FlinkKafkaProducer<WaterSensor>(
                "default",
                new KafkaSerializationSchema<WaterSensor>() {
                    @Override
                    public ProducerRecord<byte[], byte[]> serialize(WaterSensor ele,
                                                                    @Nullable Long timestamp) {
                        
                        //                        return new ProducerRecord<byte[], byte[]>("s4",
                        //                                                                  ele.getId().getBytes(StandardCharsets.UTF_8),
                        //                                                                  JSON.toJSONString(ele).getBytes(StandardCharsets.UTF_8));
                        return new ProducerRecord<byte[], byte[]>("s5",
                                                                  JSON.toJSONString(ele).getBytes(StandardCharsets.UTF_8));
                    }
                },
                props,
                FlinkKafkaProducer.Semantic.AT_LEAST_ONCE
            ));
        
        env.execute();
        
    }
}
/*
0. 当并行度小于分区数的时候, 会导致kafka的个别分区数据

1. 当向kafka写数据的时候, 让你的并行度和kafka的分区保持一致.

2. 也可以采用轮询的方式写入, 或者让kafka根据key自动计算分区索引

 */